package com.example.demo;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 应急仓库管理Servlet
 * 实现仓库信息的增删改查操作，手动处理JSON格式
 */
@WebServlet(name = "WarehouseManagementServlet", value = "/WarehouseManagementServlet")
public class WarehouseManagementServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // 数据库连接信息 - 请根据实际情况修改
    private static final String DB_URL = "jdbc:mysql://localhost/user";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    @Override
    public void init() throws ServletException {
        super.init();
        // 初始化数据库表（如果不存在）
        initializeDatabase();
    }

    /**
     * 初始化数据库表结构，包含所需的六个字段
     */
    private void initializeDatabase() {
        String createTableSQL = "CREATE TABLE IF NOT EXISTS warehouse (" +
                "id VARCHAR(36) PRIMARY KEY," +
                "name VARCHAR(100) NOT NULL COMMENT '仓库名称'," +
                "location VARCHAR(200) NOT NULL COMMENT '仓库位置'," +
                "max_capacity INT COMMENT '最大容量'," +
                "contact_person VARCHAR(50) NOT NULL COMMENT '联系人'," +
                "phone VARCHAR(20) NOT NULL COMMENT '联系电话')";

        try (Connection conn = getConnection();
             Statement stmt = conn.createStatement()) {
            stmt.execute(createTableSQL);
            System.out.println("数据库表初始化成功");
        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println("数据库表初始化失败: " + e.getMessage());
        }
    }

    /**
     * 获取数据库连接
     */
    private Connection getConnection() throws SQLException {
        try {
            // 加载MySQL驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new SQLException("MySQL驱动加载失败");
        }
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String action = request.getParameter("action");

        try {
            if (action == null) {
                // 查询所有仓库
                List<Warehouse> warehouses = getAllWarehouses();
                out.print(convertWarehousesToJson(warehouses));
            } else if (action.equals("get")) {
                // 根据ID查询单个仓库
                String id = request.getParameter("id");
                Warehouse warehouse = getWarehouseById(id);
                out.print(convertWarehouseToJson(warehouse));
            } else {
                out.print(createResultJson(false, "无效的操作"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            out.print(createResultJson(false, "数据库操作失败: " + e.getMessage()));
        } finally {
            out.flush();
            out.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String action = request.getParameter("action");
        String resultJson = createResultJson(false, "未知错误");

        try {
            if (action.equals("add")) {
                // 添加新仓库
                String name = request.getParameter("name");
                String location = request.getParameter("location");
                String maxCapacityStr = request.getParameter("maxCapacity");
                String contactPerson = request.getParameter("contactPerson");
                String phone = request.getParameter("phone");

                // 处理最大容量（可能为空）
                Integer maxCapacity = null;
                if (maxCapacityStr != null && !maxCapacityStr.isEmpty()) {
                    try {
                        maxCapacity = Integer.parseInt(maxCapacityStr);
                    } catch (NumberFormatException e) {
                        resultJson = createResultJson(false, "最大容量必须是数字");
                        out.print(resultJson);
                        out.flush();
                        out.close();
                        return;
                    }
                }

                String id = UUID.randomUUID().toString();
                boolean success = addWarehouse(id, name, location, maxCapacity, contactPerson, phone);
                resultJson = createResultJson(success, success ? "仓库添加成功" : "仓库添加失败");
            } else if (action.equals("update")) {
                // 更新仓库信息
                String id = request.getParameter("id");
                String name = request.getParameter("name");
                String location = request.getParameter("location");
                String maxCapacityStr = request.getParameter("maxCapacity");
                String contactPerson = request.getParameter("contactPerson");
                String phone = request.getParameter("phone");

                // 处理最大容量（可能为空）
                Integer maxCapacity = null;
                if (maxCapacityStr != null && !maxCapacityStr.isEmpty()) {
                    try {
                        maxCapacity = Integer.parseInt(maxCapacityStr);
                    } catch (NumberFormatException e) {
                        resultJson = createResultJson(false, "最大容量必须是数字");
                        out.print(resultJson);
                        out.flush();
                        out.close();
                        return;
                    }
                }

                boolean success = updateWarehouse(id, name, location, maxCapacity, contactPerson, phone);
                resultJson = createResultJson(success, success ? "仓库更新成功" : "仓库更新失败");
            } else if (action.equals("delete")) {
                // 删除仓库
                String id = request.getParameter("id");
                boolean success = deleteWarehouse(id);
                resultJson = createResultJson(success, success ? "仓库删除成功" : "仓库删除失败");
            } else {
                resultJson = createResultJson(false, "无效的操作");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            resultJson = createResultJson(false, "数据库操作失败: " + e.getMessage());
        } finally {
            out.print(resultJson);
            out.flush();
            out.close();
        }
    }

    /**
     * 将仓库列表转换为JSON字符串
     */
    private String convertWarehousesToJson(List<Warehouse> warehouses) {
        if (warehouses == null || warehouses.isEmpty()) {
            return "[]";
        }

        StringBuilder json = new StringBuilder("[");
        for (int i = 0; i < warehouses.size(); i++) {
            Warehouse warehouse = warehouses.get(i);
            json.append(convertWarehouseToJson(warehouse));
            if (i < warehouses.size() - 1) {
                json.append(",");
            }
        }
        json.append("]");
        return json.toString();
    }

    /**
     * 将单个仓库对象转换为JSON字符串
     */
    private String convertWarehouseToJson(Warehouse warehouse) {
        if (warehouse == null) {
            return "{}";
        }

        // 处理字符串中的双引号，避免破坏JSON格式
        String name = escapeJson(warehouse.getName());
        String location = escapeJson(warehouse.getLocation());
        String contactPerson = escapeJson(warehouse.getContactPerson());
        String phone = escapeJson(warehouse.getPhone());

        // 构建JSON字符串，处理可能为null的最大容量
        StringBuilder json = new StringBuilder();
        json.append("{\"id\":\"").append(warehouse.getId()).append("\"");
        json.append(",\"name\":\"").append(name).append("\"");
        json.append(",\"location\":\"").append(location).append("\"");

        if (warehouse.getMaxCapacity() != null) {
            json.append(",\"maxCapacity\":").append(warehouse.getMaxCapacity());
        } else {
            json.append(",\"maxCapacity\":null");
        }

        json.append(",\"contactPerson\":\"").append(contactPerson).append("\"");
        json.append(",\"phone\":\"").append(phone).append("\"}");

        return json.toString();
    }

    /**
     * 创建操作结果的JSON字符串
     */
    private String createResultJson(boolean success, String message) {
        // 处理消息中的特殊字符
        String escapedMessage = escapeJson(message);
        return String.format("{\"success\":%b,\"message\":\"%s\"}", success, escapedMessage);
    }

    /**
     * 转义JSON中的特殊字符
     */
    private String escapeJson(String value) {
        if (value == null) {
            return "";
        }
        return value.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }

    /**
     * 获取所有仓库信息
     */
    private List<Warehouse> getAllWarehouses() throws SQLException {
        List<Warehouse> warehouses = new ArrayList<>();
        String sql = "SELECT * FROM warehouse";

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            while (rs.next()) {
                Warehouse warehouse = new Warehouse(
                        rs.getString("id"),
                        rs.getString("name"),
                        rs.getString("location"),
                        rs.getInt("max_capacity"),
                        rs.getString("contact_person"),
                        rs.getString("phone")
                );
                warehouses.add(warehouse);
            }
        }
        return warehouses;
    }

    /**
     * 根据ID获取仓库信息
     */
    private Warehouse getWarehouseById(String id) throws SQLException {
        String sql = "SELECT * FROM warehouse WHERE id = ?";

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, id);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return new Warehouse(
                            rs.getString("id"),
                            rs.getString("name"),
                            rs.getString("location"),
                            rs.getInt("max_capacity"),
                            rs.getString("contact_person"),
                            rs.getString("phone")
                    );
                }
            }
        }
        return null;
    }

    /**
     * 添加新仓库
     */
    private boolean addWarehouse(String id, String name, String location, Integer maxCapacity,
                                 String contactPerson, String phone) throws SQLException {
        String sql = "INSERT INTO warehouse (id, name, location, max_capacity, contact_person, phone) " +
                "VALUES (?, ?, ?, ?, ?, ?)";

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, id);
            stmt.setString(2, name);
            stmt.setString(3, location);

            // 处理可能为null的最大容量
            if (maxCapacity != null) {
                stmt.setInt(4, maxCapacity);
            } else {
                stmt.setNull(4, Types.INTEGER);
            }

            stmt.setString(5, contactPerson);
            stmt.setString(6, phone);

            return stmt.executeUpdate() > 0;
        }
    }

    /**
     * 更新仓库信息
     */
    private boolean updateWarehouse(String id, String name, String location, Integer maxCapacity,
                                    String contactPerson, String phone) throws SQLException {
        String sql = "UPDATE warehouse SET name = ?, location = ?, max_capacity = ?, " +
                "contact_person = ?, phone = ? WHERE id = ?";

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, name);
            stmt.setString(2, location);

            // 处理可能为null的最大容量
            if (maxCapacity != null) {
                stmt.setInt(3, maxCapacity);
            } else {
                stmt.setNull(3, Types.INTEGER);
            }

            stmt.setString(4, contactPerson);
            stmt.setString(5, phone);
            stmt.setString(6, id);

            return stmt.executeUpdate() > 0;
        }
    }

    /**
     * 删除仓库
     */
    private boolean deleteWarehouse(String id) throws SQLException {
        String sql = "DELETE FROM warehouse WHERE id = ?";

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, id);
            return stmt.executeUpdate() > 0;
        }
    }

    // 仓库实体类
    public static class Warehouse {
        private String id;
        private String name;        // 仓库名称
        private String location;    // 仓库位置
        private Integer maxCapacity; // 最大容量
        private String contactPerson; // 联系人
        private String phone;       // 联系电话

        public Warehouse(String id, String name, String location, Integer maxCapacity,
                         String contactPerson, String phone) {
            this.id = id;
            this.name = name;
            this.location = location;
            this.maxCapacity = maxCapacity;
            this.contactPerson = contactPerson;
            this.phone = phone;
        }

        // Getters and Setters
        public String getId() { return id; }
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getLocation() { return location; }
        public void setLocation(String location) { this.location = location; }
        public Integer getMaxCapacity() { return maxCapacity; }
        public void setMaxCapacity(Integer maxCapacity) { this.maxCapacity = maxCapacity; }
        public String getContactPerson() { return contactPerson; }
        public void setContactPerson(String contactPerson) { this.contactPerson = contactPerson; }
        public String getPhone() { return phone; }
        public void setPhone(String phone) { this.phone = phone; }
    }
}
